import { Message, Type, load } from 'protobufjs';
export type Messages = Message<{}> | { [k: string]: any };
export type DecodeMessage = {
  protoSrc?: string;
  typeName?: string;
  uint8Array?: Uint8Array;
};

export const useLoadProtoGetType = async ({ typeName, protoSrc }: DecodeMessage) => {
  const proto = await new Promise((resolve) => {
    load(protoSrc!, (err, root) => {
      if (err) throw err;
      const proto = root?.lookupType(typeName!);
      resolve(proto);
    });
  });
  return proto as Type;
};

export const useDecodeBufferHook = async ({ protoSrc, typeName, uint8Array }: DecodeMessage) => {
  if (!uint8Array) return '';
  const protoType = await useLoadProtoGetType({ typeName, protoSrc });
  const decodeData = protoType?.decode(uint8Array);
  return decodeData;
};
